<?php include("includes/session.php"); ?>
<?php include("includes/connect_db.php"); ?>
<?php include("includes/header.php"); ?>
<?php include("notif.php"); ?>

<style>
	div{
		font-family: 'SEGOE UI';
	}
	h4{
		color : #0088cc;
	}
	#penerima{
		background-color: #fff;
		margin-left: 0px;
		margin-right: -20x;
		padding-left: 10px;
		padding-top: 5px;
		text-align: left;
		border: 1px solid #DDD;
	}
	#penerima span{
		background-color: #fff;
		padding: 1px 3px;
		border: 1px solid #DDD;
		border-radius: 5px;
		margin-right: 10px;
		margin-top: 10px;
	}
	#penerima span:hover{
		background: #EEE;
		cursor: pointer;
	}
	#text-nama, #text-nama:focus{
		border: none;
		box-shadow: none;
		margin-top: 5px;
	}
	.row-fluid{
		min-height: 10px;
	}
	.pos2{
		padding: 5px 15px;
		background-color: #0088cc; 
		color: #FFF;
		margin-left: 5px;
		float: left;
		vertical-align: center;
		border-radius: 5px;
	}
	.isi_pesan{
		width: 95%; 
		height: 200px; 
		overflow: hidden; 
		word-wrap: break-word; 
		resize: none;
	}
	#submit{
		width: 80px;
	}
	.close{
		color: #FFF;
	}
	.btn{
		width: 100px;
	}
</style>

<?php
	if (empty($_GET)) {
		$aksi = "";
		$id = "";
		$penerima = "";
		$pesan = "";
	} else {
		$aksi = $_GET['aksi'];
		$id = $_GET['id'];
	}

	if ($aksi == 1) {
		$sql_cek_draft = "SELECT * FROM tb_draft WHERE id_draft = '$id'";
		$query_cek_draft = mysql_query($sql_cek_draft);
		while ($cek_draft = mysql_fetch_array($query_cek_draft)) {
			$pesan = $cek_draft['pesan'];
			$penerima = $cek_draft['penerima'];
		}
	} elseif ($aksi == 2){
		$sql_cari_nomor = "SELECT senderNumber FROM inbox WHERE ID = '$id'";
		$query_cari_nomor = mysql_query($sql_cari_nomor);
		$cari_nomor = mysql_fetch_array($query_cari_nomor);

		$sql_cari_nama = "SELECT * FROM tb_kontak Where no_hp = '$cari_nomor[senderNumber]'";
		if ($query_cari_nama = mysql_query($sql_cari_nama)) {
			if ($cari_nama = mysql_fetch_array($query_cari_nama)) {
				$penerima = $cari_nama['nama_kontak'];
			} else{
				$penerima = $cari_nomor['senderNumber'];
			}

			$nomor = $cari_nomor['senderNumber'];
		} else {
			$penerima = $cari_nomor['senderNumber'];
		}

	} elseif ($aksi == 3) {
		$sql_cari_pesan = "SELECT textDecoded FROM inbox WHERE ID = '$id'";
		$query_cari_pesan = mysql_query($sql_cari_pesan);
		$cari_pesan = mysql_fetch_array($query_cari_pesan);

		$pesan = $cari_pesan['textDecoded'];
	} elseif ($aksi == 4){
		$sql_cari_nomor = "SELECT destinationNumber FROM sentitems WHERE ID = '$id'";
		$query_cari_nomor = mysql_query($sql_cari_nomor);
		$cari_nomor = mysql_fetch_array($query_cari_nomor);

		$sql_cari_nama = "SELECT * FROM tb_kontak Where no_hp = '$cari_nomor[destinationNumber]'";
		$query_cari_nama = mysql_query($sql_cari_nama);
		if ($cari_nama = mysql_fetch_array($query_cari_nama)) {
			$penerima = $cari_nama['nama_kontak'];
		} else{
			$penerima = $cari_nomor['destinationNumber'];
		}

		$nomor = $cari_nomor['destinationNumber'];
	} elseif ($aksi == 5) {
		$sql_cari_pesan = "SELECT textDecoded FROM sentitems WHERE ID = '$id'";
		$query_cari_pesan = mysql_query($sql_cari_pesan);
		$cari_pesan = mysql_fetch_array($query_cari_pesan);

		$pesan = $cari_pesan['textDecoded'];
	}
?>

<div class="span9">  
    <h3>SMS</h3>                      
    <ul class="breadcrumb well">
        <li class="active">Pesan Baru</li>                
    </ul>    
    <h4>Buat Pesan Baru</h4>
    <div style="width: 100%">
		<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
			<div class="row-fluid">
				<input id="text-nama-hidden" type="text" data-provide="tag" value="<?php echo $penerima; ?>">
				<input id="penerima-hide" name="penerima_hide" type="hidden" value="<?php echo $penerima; ?>">
				<a href="#">
					<div class="pos2" id="cari_kontak">
						<div style="margin-left: 15px; padding-top: 5px"><i class="icon-user icon-white"></i></div>
						<div style="margin-top: -5px;">Kontak</div>
				</div></a>
			</div>
			<div><b>Pesan</b></div>
			<div class="control-group">
				<textarea name="pesan" class="isi_pesan"><?php echo $pesan ?></textarea>
			</div>
			<div class="control-group">
				<div class="controls">
					<button type="submit" class="btn btn-info" name="kirim">
						<i class="icon-white icon-ok"></i>
						Kirim
					</button>
					<button type="submit" class="btn" name="simpan">
						<i class="icon-download-alt"></i>
						Simpan
					</button>
					<button type="submit" class="btn btn-danger" name="batal">
						<i class="icon-white icon-remove"></i>
						Batal
					</button>
				</div>
			</div>
		</form>
	</div>

	<?php
		if (empty($_POST)) {
			$penerima_hide = "";
			$pesan = "";
		} else {
			$penerima_hide = $_POST['penerima_hide'];
			$pesan = $_POST['pesan'];
		}
		
		if (isset($_POST['simpan'])) {
			$sql_simpan_pesan = "INSERT INTO tb_draft (penerima, pesan, waktu) Value ('$penerima_hide', '$pesan', $waktu)";
			$query_simpan_pesan = mysql_query($sql_simpan_pesan) or die(mysql_error());

			if ($query_simpan_pesan) {
				if ($aksi == 1) {
					echo "<SCRIPT> alert('Pesan Disimpan Pada Draft'); location.href='draft.php';</SCRIPT>";
				} elseif ($aksi == 2 or $aksi == 3){
					echo "<SCRIPT> alert('Pesan Disimpan Pada Draft'); location.href='inbox.php';</SCRIPT>";
				} elseif ($aksi == 4 or $aksi == 5){
					echo "<SCRIPT> alert('Pesan Disimpan Pada Draft'); location.href='outbox.php';</SCRIPT>";
				} else {
					echo "<SCRIPT> alert('Pesan Disimpan Pada Draft'); location.href='inbox.php';</SCRIPT>";
				}
			} else {
				echo "<SCRIPT> alert('Data Gagal Disimpan');</SCRIPT>";
			}
		} elseif (isset($_POST['batal'])) {
			if ($aksi == 1) {
				echo "<SCRIPT> location.href='draft.php';</SCRIPT>";
			} elseif ($aksi == 2 or $aksi == 3){
				echo "<SCRIPT> location.href='inbox.php';</SCRIPT>";
			} elseif ($aksi == 4 or $aksi == 5){
				echo "<SCRIPT> location.href='outbox.php';</SCRIPT>";
			} else{
				echo "<SCRIPT> location.href='inbox.php';</SCRIPT>";
			}
		} elseif (isset($_POST['kirim'])) {
			$nomor = explode(',', $penerima_hide);
			$jum = count($nomor);
			$i = 0;
			foreach ($nomor as $nomor_kirim) {
				$jmlSMS = ceil(strlen($pesan)/153);
				$pecah  = str_split($pesan, 153);

				$sql_cek_group = "SELECT * FROM tb_group_kontak WHERE nama_group = '$nomor_kirim'";
				$query_cek_group = mysql_query($sql_cek_group);
				$jumlah_cek_group = mysql_num_rows($query_cek_group);

				if ($jumlah_cek_group > 0) {
					$query_cek_group = mysql_query($sql_cek_group);
					$cek_group = mysql_fetch_array($query_cek_group);

					$sql_cari_kontak = "SELECT * FROM tb_detail_kontak WHERE id_group = '$cek_group[id_group]'";
					$query_cari_kontak = mysql_query($sql_cari_kontak);
					while ($cari_kontak = mysql_fetch_array($query_cari_kontak)) {
						$sql = "SELECT * FROM tb_kontak WHERE id_kontak = '$cari_kontak[id_kontak]'";
						$query = mysql_query($sql);
						$kontak = mysql_fetch_array($query);
						$nomor_kirim = $kontak['no_hp'];

						$query = "SHOW TABLE STATUS LIKE 'outbox'";
						$hasil = mysql_query($query);
						$data  = mysql_fetch_array($hasil);
						$newID = $data['Auto_increment'];	

						if ($jmlSMS == 1) {
							$sql_kirim_pesan = "insert into outbox 
						    						(TextDecoded, DestinationNumber, CreatorID) 
						    					values 
						    						('$pesan', '$nomor_kirim', '')";

						    if ($query_kirim_pesan = mysql_query($sql_kirim_pesan)){
						    	$bantu = 1;
						    }
						} elseif ($jmlSMS > 1) {
							for ($i=1; $i<=$jmlSMS; $i++) {
							   	$udh = "050003A7".sprintf("%02s", $jmlSMS).sprintf("%02s", $i);

							   	$msg = $pecah[$i-1];

							   	if ($i == 1) {
							      	$sql_kirim_pesan = "INSERT INTO outbox (DestinationNumber, UDH, TextDecoded, ID, MultiPart, CreatorID)
							                			VALUES ('$nomor_kirim', '$udh', '$msg', '$newID', 'true', '')";

							   	} else { 
							      	$sql_kirim_pesan = "INSERT INTO outbox_multipart(UDH, TextDecoded, ID, SequencePosition)
							                			VALUES ('$udh', '$msg', '$newID', '$i')";
							   	} 
								
								if ($query_kirim_pesan = mysql_query($sql_kirim_pesan)){
							    	$bantu = 1;
							    }
							}
						}
					    $i++;	
					}
				} else {
					$query = "SHOW TABLE STATUS LIKE 'outbox'";
					$hasil = mysql_query($query);
					$data  = mysql_fetch_array($hasil);
					$newID = $data['Auto_increment'];
					$validator = "";

					$sql_cek_kontak = "SELECT no_hp FROM tb_kontak_rincian where nama_rincian = '$nomor_kirim'";
					$query_cek_kontak = mysql_query($sql_cek_kontak);
					$hitung_baris = mysql_num_rows($query_cek_kontak);

					if ($hitung_baris != 0) {
						$query_cek_kontak = mysql_query($sql_cek_kontak);
						$cek_kontak = mysql_fetch_array($query_cek_kontak);
						$nomor_kirim = $cek_kontak[0];
					} elseif (is_numeric($nomor_kirim)) {
						if ($nomor_kirim[0] == '0') {
							$panjang = strlen($nomor_kirim);
							if ($panjang <= 12) {
								$nomor_kirim = "+62".substr($nomor_kirim, 1, $panjang-1);
							}
						} elseif ($nomor_kirim[0] == '+' and $nomor_kirim[1] == '6' and $nomor_kirim[2] == '2') {
							$panjang = strlen($nomor_kirim);

							$nomorBaru = substr($nomor_kirim, 3, $panjang-3);
							$panjang2 = strlen($nomorBaru);
							$nomorBaru2 = (int)$nomorBaru;
							$panjang3 = strlen($nomorBaru2);

							if ($panjang2 <= 12) {
								if ($panjang2 == $panjang3) {
									$nomor_kirim = "+62".$nomorBaru;
								}
							}
						}
					} else {
						$validator = 1;
					}

					if ($validator != 1) {
						if ($jmlSMS == 1) {
							$sql_kirim_pesan = "insert into outbox 
						    						(TextDecoded, DestinationNumber, CreatorID) 
						    					values 
						    						('$pesan', '$nomor_kirim', '')";

						    if ($query_kirim_pesan = mysql_query($sql_kirim_pesan)){
						    	$bantu = 1;
						    } else{
						 		echo "<SCRIPT> alert('Data Gagal Dikirim');</SCRIPT>";   	
						    }
						} elseif ($jmlSMS > 1) {
							for ($i=1; $i<=$jmlSMS; $i++) {
							   	$udh = "050003A7".sprintf("%02s", $jmlSMS).sprintf("%02s", $i);

							   	$msg = $pecah[$i-1];

							   	if ($i == 1) {
							      	$sql_kirim_pesan = "INSERT INTO outbox (DestinationNumber, UDH, TextDecoded, ID, MultiPart, CreatorID)
							                			VALUES ('$nomor_kirim', '$udh', '$msg', '$newID', 'true', '')";

							   	} else { 
							      	$sql_kirim_pesan = "INSERT INTO outbox_multipart(UDH, TextDecoded, ID, SequencePosition)
							                			VALUES ('$udh', '$msg', '$newID', '$i')";
							   	} 
								
								if ($query_kirim_pesan = mysql_query($sql_kirim_pesan)){
							    	$bantu = 1;
							    } else{
							 		echo "<SCRIPT> alert('Data Gagal Dikirim');</SCRIPT>";   	
						    	}
							}
						}
					    $i++;
					}
				}
				

		    	if ($aksi == 1) {
		    		if ($bantu == 1) {
						echo "<SCRIPT> alert('Pesan Berhasil Dikirim'); location.href='draft.php';</SCRIPT>";
		    		} else{
		    			echo "<SCRIPT> location.href='draft.php';</SCRIPT>";
		    		}
				} elseif ($aksi == 2 or $aksi == 3) {
					if ($bantu == 1) {
						echo "<SCRIPT> alert('Pesan Berhasil Dikirim'); location.href='inbox.php';</SCRIPT>";
		    		} else{
		    			echo "<SCRIPT> location.href='inbox.php';</SCRIPT>";
		    		}
				}  elseif ($aksi == 4 or $aksi == 5) {
					if ($bantu == 1) {
						echo "<SCRIPT> alert('Pesan Berhasil Dikirim'); location.href='outbox.php';</SCRIPT>";
		    		} else{
		    			echo "<SCRIPT> location.href='outbox.php';</SCRIPT>";
		    		}
				} else {
					if ($bantu == 1) {
						echo "<SCRIPT> alert('Pesan Berhasil Dikirim'); location.href='inbox.php';</SCRIPT>";
		    		} else{
		    			echo "<SCRIPT> location.href='inbox.php';</SCRIPT>";
		    		}
				}
			}
		}
	?>
    	

</div><!--/span-->

<?php include("includes/footer.php"); ?>

<script type="text/javascript">
    var namaArr = [];
    var nomorArr = [];
    $(document).ready(function() {
    	
        $('.text-auto-nama').typeahead({
          source: function(typeahead, query) {
            $.ajax({
              url: "act_user.php?act=1",
              dataType: "json",
              type: "POST",
              data: {key: query},
              success: function(data) {
              	alert("haha");
                var return_list = [], i = data.length;
                while (i--) {
                  return_list[i] = {id: data[i].id, value: data[i].nomor +" | "+ data[i].nama, nama: data[i].nama};
                }
                typeahead.process(return_list);
              }
            });
          },
          onselect: function(obj) {
            // console.log(obj);
            $('#user-name').val(obj.nama);
            $('#user-id').val(obj.id);
            // $('input[id="MessageUserId"]').val(obj.id);
          }
        });

	    if($("#penerima-hide").val()!=""){
	    	namaArr = $("#penerima-hide").val().split(',')
	    }

		$('#cari_kontak').live('click',function(){
			tempView = $(this);
	        $("#tampil-modal").fadeOut("medium",function(){
	        	// console.log($('#tampil-modal').html());
	        	if($('#tampil-modal').html()==""){
		            $.ajax({
		                url: "compose-modal.php", 
		                cache: false, 
		                success: function(kontak){ 
		                    $("#tampil-modal").html(kontak);
		                    $("#tampil-modal").fadeIn("medium");
		                    cekKontak();
		                } 
		            }); 
	        	}else{
	        		$('#form-modal').modal('show');
	        		cekKontak();
	        	}
	        });
	        return false;
		});
    });
</script>